/*
输出按键,判断按键长按还是短按
//无法支持全键无冲
*/
module button (
	input clk,
	// input clk_1k,
	input rst_n,
	input [3:0] button_in,				//按键输入，对应四个独立按键，3->0分别是k1->k4
	output wire [3:0] button_out,		//
	output wire [3:0] button_posedge,	//按钮上升沿信号
	output reg [3:0] button_long		//按钮长信号
	// output wire button_mode 			//0代表短按，1代表长按
);

	parameter MAX_TIME = 1000 * 50 * 499;		//ms

	reg [31:0] count [3:0];
	wire [3:0] button_temp;
	wire [3:0] button_long_cache;

	// assign button_mode = (count >= MAX_TIME)? 1:0;
	assign button_long_cache[3] = (count[3] >= MAX_TIME)? 1'b1:1'b0;
	assign button_long_cache[2] = (count[2] >= MAX_TIME)? 1'b1:1'b0;
	assign button_long_cache[1] = (count[1] >= MAX_TIME)? 1'b1:1'b0;
	assign button_long_cache[0] = (count[0] >= MAX_TIME)? 1'b1:1'b0;
	always @(posedge clk) begin
		button_long <= button_long_cache;
	end

	assign button_out = button_temp;

	always @(posedge clk or negedge rst_n) begin
		if (rst_n == 1'b0) begin
			// button_mode <= 0;
			// button_out <= 4'b1111;
			count[3] <= 0;
			count[2] <= 0;
			count[1] <= 0;
			count[0] <= 0;
		end
		else begin
			case (button_temp)
				4'b0111:count[3] <= (count[3] >= MAX_TIME)? count[3]:(count[3] + 1);
				4'b1011:count[2] <= (count[2] >= MAX_TIME)? count[2]:(count[2] + 1);
				4'b1101:count[1] <= (count[1] >= MAX_TIME)? count[1]:(count[1] + 1);
				4'b1110:count[0] <= (count[0] >= MAX_TIME)? count[0]:(count[0] + 1);
				4'b1111:begin
					count[3] <= 0;
					count[2] <= 0;
					count[1] <= 0;
					count[0] <= 0;
				end
				default: begin
					count[3] <= 0;
					count[2] <= 0;
					count[1] <= 0;
					count[0] <= 0;
				end
			endcase
		end
	end


	ax_debounce ax_debounce_k1		//按键消抖
	(		
	.clk             (clk),
	.rst_n           (rst_n),
	.button_in       (button_in[3]),
	.button_posedge  (button_posedge[3]),
	.button_negedge  (),
	.button_out      (button_temp[3])
	);
	ax_debounce ax_debounce_k2		//按键消抖
	(		
	.clk             (clk),
	.rst_n           (rst_n),
	.button_in       (button_in[2]),
	.button_posedge  (button_posedge[2]),
	.button_negedge  (),
	.button_out      (button_temp[2])
	);
	ax_debounce ax_debounce_k3		//按键消抖
	(		
	.clk             (clk),
	.rst_n           (rst_n),
	.button_in       (button_in[1]),
	.button_posedge  (button_posedge[1]),
	.button_negedge  (),
	.button_out      (button_temp[1])
	);
	ax_debounce ax_debounce_k4		//按键消抖
	(		
	.clk             (clk),
	.rst_n           (rst_n),
	.button_in       (button_in[0]),
	.button_posedge  (button_posedge[0]),
	.button_negedge  (),
	.button_out      (button_temp[0])
	);
	
endmodule